//
//  XQOrderPageController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/4.
//

import UIKit
import MJRefresh

class XQOrderPageController: UIViewController {

    var orderPageId = ""
    
    var dataSource: [XQOrderReadingsModel]?
    
    private lazy var emptyImageView : UIImageView = {
       let imageView = UIImageView()
        imageView.image = UIImage(named:"order_empty")
        return imageView
    }()
    
    private lazy var tableView : UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 152
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(XQOrderCell.self, forCellReuseIdentifier: "XQOrderCell")
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.refreshData()
        })
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        makeUI()
        makeConstraints()
        
        XQHud.showLoading(controller: self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshData()
    }
    
    private func makeUI() {
        self.view.addSubview(self.emptyImageView)
        self.view.addSubview(self.tableView)
    }
    
    private func refreshData() {
        let params : [String : String] = [
            "cohen" : self.orderPageId
        ]
        
        XQNetworkManager.shared.postRequest(url: "/figures/consistent", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud .hideLoading(controller: srongify)
            srongify.tableView.mj_header?.endRefreshing()
            if (response?.object == 0) {
                if let model = XQOrderModel.deserialize(from: response?.procedure) {
                    if (model.readings?.count == 0) {
                        srongify.updatePageStatus(status: 0)
                    }else {
                        srongify.updatePageStatus(status: 1)
                    }
                    srongify.dataSource = model.readings
                    srongify.tableView.reloadData()
                }
            }else {
                srongify.updatePageStatus(status: 0)
            }
        }
    }

    private func makeConstraints() {
        self.emptyImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-50)
            make.width.equalTo(197)
            make.height.equalTo(208)
        }
        self.tableView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(-8)
        }
    }
   
    private func updatePageStatus(status : Int) {
        self.emptyImageView.isHidden = status != 0
        self.tableView.isHidden = status != 1
    }
}

extension XQOrderPageController : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XQOrderCell", for: indexPath) as! XQOrderCell
        if let datas = dataSource {
            if (indexPath.row < datas.count) {
                cell.model = datas[indexPath.row]
            }
        }
        cell.protocolHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.jumpProtocol(indexPath: indexPath)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let datas = dataSource else {return}
        
        if indexPath.row >= datas.count {return}
        
        let model = datas[indexPath.row]
        
        guard let url = model.decide else {return}
        
        XQRouteTool.jumpController(controller: self, url: url)
    }
    
    private func jumpProtocol(indexPath : IndexPath) {
        guard let datas = dataSource else {return}
        
        if indexPath.row >= datas.count {return}
        
        let model = datas[indexPath.row]
        
        guard let url = model.elimination else {return}
        
        if (!url.isEmpty) {
            XQRouteTool.jumpWebController(controller: self, url: XQNetworkManager.shared.getWebUrlAbsolutePath(path: url))
        }
    }
}
